package util

import (
	"bytes"
	"reflect"
	"unsafe"

	stdlog "log"

	log "github.com/sirupsen/logrus"
)

type logrusFormatter struct {

}

/**
日志配置
2021-12-24 10:16:03.201 []  INFO --- [ing.beat.sender] com.alibaba.nacos.client.naming          : msg
*/
func (t * logrusFormatter) Format(entry *log.Entry) ([]byte, error) {
	buf := &bytes.Buffer{}

	t.writeString(buf, entry.Time.Format("2006-01-02 15:04:05.000"))
	t.writeString(buf, " [] ") //不支持trace
	t.writeString(buf, entry.Level.String())
	t.writeString(buf, " --- ")
	t.writeString(buf, "[none] ") //不支持thread id
	t.writeString(buf, "none ")   //不支持logger name
	t.writeString(buf, ": ")
	t.writeString(buf, entry.Message)
	t.writeString(buf, "\r\n")

	return buf.Bytes(), nil
}

func (t *logrusFormatter) writeString(buf *bytes.Buffer, s ...string) {
	for _, str := range s {
		buf.Write(string2Bytes(str))
	}
}

func string2Bytes(s string) (data []byte) {
	p := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)

	h := (*reflect.SliceHeader)(unsafe.Pointer(&data))
	h.Cap = len(s)
	h.Len = len(s)
	h.Data = uintptr(p)
	return data
}

type stdlogWriter struct {

}

/**
标准日志库通过logrus输出
*/
func (w *stdlogWriter) Write(data []byte) (int, error) {
	log.Print(data)
	return 0, nil
}

func InitLogConfig() {
	log.SetFormatter(&logrusFormatter{})
	stdlog.SetOutput(&stdlogWriter{})
}